/**
 * Created by djh on 2016/10/31.
 *
 * 每个项目的任务基本相同，但是路径可能会有点区别，所以这里 用参数区分: member、mpe
 */

var gulp = require("gulp"),
    argv = require("yargs").argv,
    $    = require("gulp-load-plugins")(),
    pump = require("pump"),//能精确地报错，而不是报nodejs的错
    browserSync = require('browser-sync').create();
var cleanCSS = require('gulp-clean-css'); //压缩css

var uglify_config = {
    mangle: {except: ['define', 'require', 'module', 'exports']},
    compress: false
};

var app_type = 'mpe'; //应用类型
var html ="default"; //模板文件夹
if(argv.mpeAdmin) {
    app_type ='mpeAdminNew';
    html="new";
}

//path 默认路径
var baseDir = {
    js:'./res/'+app_type+'/js/',
    scss:'./res/'+app_type+'/scss/',
    html: './www/mpe/modules/'+app_type+'/template/'+html+'/**/*.html'
};



//编译css 用于开发环境 -- 但是一个scss编译出错， 修改后，间接调用scss不修改，他就不更新，神烦
gulp.task('compass', function() {
    gulp.src([baseDir.scss+'*.scss',baseDir.scss+'**/*.scss'])
        //.pipe($.plumber())
        .pipe($.compass({
            style:'compact',
            relative: true,
            image: baseDir.scss+'icons',//图片精灵用来存放的位置
            css: baseDir.scss+'css',
            sass: baseDir.scss
            //此处有一坑，注意一定要配置css 跟sass选项，官方文档中有说明，
        }))
        .on("error",function(e){
            console.log(e);
        })
        .pipe(gulp.dest(baseDir.scss+'css'))
        .pipe($.notify({
            message: "scss编译完成",
            onLast:true
        }))
        .pipe($.rename({
            suffix:"$min_suffix"
        }))
        .pipe($.revUyes())
        .pipe($.revUyes.manifest())
        .pipe(gulp.dest(baseDir.scss+"rev"))
        .pipe(browserSync.reload({stream:true}));
});


//压缩版css 用于部署环境
gulp.task('minicss',function() {
    return gulp.src([
        baseDir.scss+'css/*.css',
        '!'+baseDir.scss+'css/*-min.css',
        baseDir.scss+'css/**/*.css',
        '!'+baseDir.scss+'css/**/*-min.css'])
        .pipe(cleanCSS({compatibility: 'ie8',debug:true}))
        .pipe($.rename({
            suffix:"-min"
        }))
        .pipe(gulp.dest(baseDir.scss+'css'))
        .pipe($.size({title: 'minicss',pretty:true,showFiles:true}))

});
//部署css
gulp.task('rev_css',['minicss'],function() {
    return gulp.src([baseDir.scss+'rev/rev-manifest.json',baseDir.scss+'rev/csslink.html'])
        .pipe($.revCollectorUyes())
        .pipe(gulp.dest("www/mpe/modules/member/template/default/inc/"))
        .pipe(
            $.notify({
                "message":"end----------------css文件发布完成------------------",
                "onLast": true,
                "wait": true
            }))
});

// 清空文件夹 -主要用于有时候重新编译scss
gulp.task('clean', function() {
    if(argv.js) {
        gulp.src([baseDir.js+'dist'], {read: false})
            .pipe($.clean());
    }else if(argv.css){
        gulp.src([baseDir.scss+'css'], {read: false})
            .pipe($.clean());
    }else if(argv.minjs){
        gulp.src([baseDir.js+'*-min.js',baseDir.js+'**/*min.js'], {read: false})
            .pipe($.clean({force: true}));
    } else {
        gulp.src([baseDir.scss+'css'], {read: false})
            .pipe($.clean());
        //console.log("你要清空什么文件，请加参数，如清空js压缩文件：gulp clean --js")
    }
});
/*js 发布几部走*/
//step1 生成rev-json 文件
gulp.task('js_revJson',function(cb){
return gulp.src([baseDir.js+'*.js','!'+baseDir.js+'*-min.js',baseDir.js+'**/*.js','!'+baseDir.js+'**/*-min.js'])
    .pipe($.revUyes())
    .pipe($.revUyes.manifest({ merge: true}))
    .pipe(gulp.dest(baseDir.js+'rev'))
    .on('end',function(){
        console.log("start----------------rev-json文件生成----------------step1");

    })
});
//step2 config.js 打版本戳
gulp.task('rev_config',['js_revJson'],function(cb){
    return gulp.src([baseDir.js+'rev/rev-manifest.json',baseDir.js+'rev/config_member.js',baseDir.js+'rev/config_web.js'])
        .pipe($.revCollectorUyes())
        .pipe(gulp.dest(baseDir.js))
        .on('end',function(){
            console.log("----------------config.js文件版本生成----------------step2");

        })
});
//step3 打了版本戳压缩js
gulp.task('uglify',['rev_config'],function (cb) {
    return gulp.src([baseDir.js+'*.js','!'+baseDir.js+'*-min.js',baseDir.js+'**/*.js','!'+baseDir.js+'**/*-min.js'])
        .pipe($.uglify(uglify_config))
        .pipe($.rename({suffix:"-min"}))
        .pipe($.size({title: 'minijs',pretty:true,showFiles:true}))
        .pipe(gulp.dest(baseDir.js))
        .on('end',function(){
            console.log("----------------js压缩完成-----------------------step3");
        })
});
//step4 给script文件打上版本戳
gulp.task('rev_js',['rev_config','uglify','js_revJson'],function(cb){
    return gulp.src([baseDir.js+'rev/rev-manifest.json',baseDir.js+"rev/script*.html"])
        .pipe($.revCollectorUyes())
        .pipe(gulp.dest("www/mpe/modules/member/template/default/inc/"))
        .pipe(
            $.notify({
                "message":"end----------------script文件发布完成------------------step4",
                "onLast": true,
                "wait": true
            }))
});

gulp.task('rev',['rev_css','rev_js'],function() {
     console.log("end----------------批量部署完成------------------");
});
//监控
gulp.task("watch",function(){
    browserSync.init({
       proxy: "http://mpe.dasu123.my/"
        //server: baseDir
    });
    gulp.watch([baseDir.scss+"*.scss",baseDir.scss+'**/*.scss',baseDir.scss+"icons/**/*.png"],["compass"],function(e){
        console.log(e);
    });
    if(!argv.mpeAdmin) {
        gulp.watch([baseDir.html, baseDir.js + "*.js"]).on("change", browserSync.reload);
    }
});

gulp.task('help',function () {
    /*
    * 需要打版本戳的文件修改需要更改rev文件夹下面的文件，直接改系统打了版本戳的文件无效，如：config_member.js
    * css/rev
    * js/rev
    *
    *
    * */
    console.log('	gulp cpmpass		编译css');
    console.log('	gulp minicss		压缩css');
    console.log('	gulp rev_css		css打上版本戳');
    console.log('	gulp rev_js		    js打上版本戳');
    console.log('	gulp rev		    css,js打上版本戳');
    console.log('	gulp clean		    删除文件夹,默认是清空css文件夹');
    console.log('	gulp watch			监控文件修改,编译scss成css，动态刷新浏览器');

});